<template>
  <div class="message-notification">
    <!-- 消息图标和未读数量 -->
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="message-badge">
      <el-button
        type="text"
        @click="toggleDropdown"
        class="message-button"
        :class="{ active: showDropdown }"
      >
        <el-icon :size="20">
          <Bell />
        </el-icon>
      </el-button>
    </el-badge>

    <!-- 消息下拉框 -->
    <div v-if="showDropdown" class="message-dropdown" v-click-outside="closeDropdown">
      <div class="dropdown-header">
        <span class="header-title">消息通知</span>
        <div class="header-actions">
          <el-button size="small" type="text" @click="markAllAsRead">
            全部已读
          </el-button>
          <el-button size="small" type="text" @click="goToMessageCenter">
            查看全部
          </el-button>
        </div>
      </div>

      <div class="dropdown-content">
        <el-scrollbar height="300px">
          <div v-if="recentMessages.length === 0" class="empty-messages">
            <el-empty description="暂无新消息" :image-size="60" />
          </div>
          
          <div v-else class="message-list">
            <div
              v-for="message in recentMessages"
              :key="message.id"
              class="message-item"
              :class="{ unread: !message.isRead }"
              @click="handleMessageClick(message)"
            >
              <div class="message-avatar">
                <el-avatar
                  :size="36"
                  :src="message.senderAvatar"
                  :icon="message.type === 'system' ? 'Bell' : 'User'"
                  :style="{ backgroundColor: message.type === 'system' ? '#f56c6c' : '#409eff' }"
                />
              </div>
              
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-name">{{ message.senderName || '系统通知' }}</span>
                  <span class="message-time">{{ formatTime(message.createTime) }}</span>
                </div>
                <div class="message-title">{{ message.title }}</div>
                <div class="message-preview">{{ message.content }}</div>
              </div>
              
              <div v-if="!message.isRead" class="unread-dot"></div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <div class="dropdown-footer">
        <el-button type="primary" size="small" @click="goToMessageCenter" block>
          进入消息中心
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Bell } from '@element-plus/icons-vue'
import { getSystemMessages, getSystemUnreadCount, markSystemMessagesRead, markSystemMessageRead } from '@/utils/apiService'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import messageStateManager from '@/utils/messageStateManager'

// 路由
const router = useRouter()

// 响应式数据
const showDropdown = ref(false)
const recentMessages = ref([])
const pollingTimer = ref(null)

// 使用全局状态管理器的数据
const unreadCount = computed(() => messageStateManager.getTotalUnreadCount())
const systemUnreadCount = messageStateManager.systemUnreadCount

// 计算属性
const hasUnreadMessages = computed(() => unreadCount.value > 0)

// 方法
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
  if (showDropdown.value) {
    loadRecentMessages()
  }
}

const closeDropdown = () => {
  showDropdown.value = false
}

const loadRecentMessages = async () => {
  try {
    const response = await getSystemMessages({
      page: 1,
      size: 10
    })

    console.log('🔍 加载最近消息响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      recentMessages.value = responseData.data || []
    } else {
      console.log('❌ 加载最近消息失败:', responseData)
    }
  } catch (error) {
    console.error('加载消息失败:', error)
  }
}

const loadUnreadCount = async () => {
  try {
    const response = await getSystemUnreadCount()

    console.log('🔍 加载未读数量响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      unreadCount.value = responseData.data?.unreadCount || 0
    } else {
      console.log('❌ 加载未读数量失败:', responseData)
    }
  } catch (error) {
    console.error('加载未读数量失败:', error)
  }
}

const markAllAsRead = async () => {
  try {
    const unreadMessageIds = recentMessages.value
      .filter(msg => !msg.isRead)
      .map(msg => msg.messageId || msg.id)

    if (unreadMessageIds.length === 0) {
      ElMessage.info('没有未读消息')
      return
    }

    // 使用全局状态管理器批量标记已读
    const success = await messageStateManager.markSystemMessagesAsRead(unreadMessageIds)

    if (success) {
      // 更新本地状态
      recentMessages.value.forEach(msg => {
        if (!msg.isRead) {
          msg.isRead = true
        }
      })

      ElMessage.success('所有消息已标记为已读')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleMessageClick = async (message) => {
  // 如果消息未读，标记为已读
  if (!message.isRead) {
    const messageId = message.messageId || message.id
    const success = await messageStateManager.markSystemMessageAsRead(messageId)

    if (success) {
      message.isRead = true
    }
  }

  // 关闭下拉框
  closeDropdown()

  // 跳转到消息中心并显示消息详情
  router.push({
    path: '/message/system',
    query: { messageId: message.messageId || message.id }
  })
}

const goToMessageCenter = () => {
  closeDropdown()
  router.push('/message')
}

const formatTime = (time) => {
  if (!time) return ''
  
  const date = new Date(time)
  const now = new Date()
  const diffInHours = (now - date) / (1000 * 60 * 60)
  
  if (diffInHours < 1) {
    return '刚刚'
  } else if (diffInHours < 24) {
    return formatDistanceToNow(date, { 
      addSuffix: true, 
      locale: zhCN 
    })
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

const startPolling = () => {
  // 每30秒检查一次未读消息
  pollingTimer.value = setInterval(() => {
    loadUnreadCount()
  }, 30000)
}

const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

// 生命周期
onMounted(() => {
  loadUnreadCount()
  loadRecentMessages()

  // 添加状态更新监听器
  messageStateManager.addStateUpdateCallback(handleStateUpdate)

  startPolling()
})

onUnmounted(() => {
  stopPolling()

  // 移除状态更新监听器
  messageStateManager.removeStateUpdateCallback(handleStateUpdate)
})

// 处理状态更新
const handleStateUpdate = (update) => {
  if (update.type === 'system') {
    if (update.action === 'new_message') {
      // 有新消息时刷新最近消息列表
      loadRecentMessages()
    } else if (update.action === 'mark_read' || update.action === 'batch_mark_read') {
      // 消息被标记已读时更新本地状态
      loadRecentMessages()
    }
  }
}

// 暴露方法给父组件
defineExpose({
  refreshUnreadCount: loadUnreadCount,
  refreshMessages: loadRecentMessages
})
</script>

<style scoped>
.message-notification {
  position: relative;
  display: inline-block;
}

.message-badge {
  display: inline-block;
}

.message-button {
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.message-button:hover,
.message-button.active {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.message-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  width: 360px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
  z-index: 1000;
  margin-top: 8px;
}

.dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.dropdown-content {
  max-height: 300px;
}

.empty-messages {
  padding: 40px 20px;
  text-align: center;
}

.message-list {
  padding: 8px 0;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
}

.message-item:hover {
  background: #f5f7fa;
}

.message-item.unread {
  background: rgba(64, 158, 255, 0.05);
}

.message-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 13px;
}

.message-time {
  font-size: 11px;
  color: #909399;
}

.message-title {
  font-size: 14px;
  color: #2c3e50;
  margin-bottom: 2px;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-preview {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.unread-dot {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 6px;
  height: 6px;
  background: #409eff;
  border-radius: 50%;
}

.dropdown-footer {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
}

/* 点击外部关闭的指令样式 */
.v-click-outside {
  position: relative;
}
</style>
